package com.it.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.it.entity.SysUser;
import com.it.utils.UtilJWT;
import com.it.vo.HttpResult;
import com.it.vo.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author: Coke
 * @DateTime: 2023/11/13/19:33
 **/
@Component
@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    // 使用此工具进行序列化
    @Autowired
    private ObjectMapper objectMapper;
    
    @Autowired
    private UtilJWT utilJWT;
    
    @Override
    public void onAuthenticationSuccess (HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 从认证对象中获取认证用户信息
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        SysUser sysUser = securityUser.getSysUser();
        String userInfo = objectMapper.writeValueAsString(sysUser);
        List<SimpleGrantedAuthority> authorities = (List<SimpleGrantedAuthority>) securityUser.getAuthorities();
        // 使用stream流
        List<String> authList = authorities.stream().map(SimpleGrantedAuthority :: getAuthority).collect(Collectors.toList());
        // 创建jwt
        String token = utilJWT.createToken(userInfo, authList);
        log.info("token= {}",token);
        // 返回给前端 token
        HttpResult httpResult = HttpResult.builder()
              .code(1)
              .msg("jwt验证成功！")
              .data(token).build();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(objectMapper.writeValueAsString(httpResult));
        writer.flush();
    }
}
